<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="理解C++虚函数表"><meta name="keywords" content="C++"><meta name="author" content="LiYang"><meta name="copyright" content="LiYang"><title>理解C++虚函数表 | 一条鲤鱼</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="一条鲤鱼" type="application/atom+xml">
</head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="Toggle article">Toggle site</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">Catalog</div><div class="sidebar-toc__progress"><span class="progress-notice">You've read</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%90%86%E8%A7%A3-C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8"><span class="toc-number">1.</span> <span class="toc-text">理解 C++ 虚函数表</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%BC%95%E8%A8%80"><span class="toc-number">2.</span> <span class="toc-text">引言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#C-%E7%B1%BB%E7%9A%84%E5%AE%9E%E8%B4%A8%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">3.</span> <span class="toc-text">C++ 类的实质是什么</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%8F%AD%E5%BC%80-vTable-%E7%9A%84%E7%A5%9E%E7%A7%98%E9%9D%A2%E7%BA%B1"><span class="toc-number">4.</span> <span class="toc-text">揭开 vTable 的神秘面纱</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">LiYang</div><div class="author-info__description text-center"></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">Articles</span><span class="pull-right">13</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">Tags</span><span class="pull-right">6</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">Categories</span><span class="pull-right">7</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">一条鲤鱼</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"></span></div><div id="post-info"><div id="post-title">理解C++虚函数表</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2021-11-10</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">编程语言</a><i class="fa fa-angle-right" aria-hidden="true"></i><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/C/">C++</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>参考：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/64f3b9c22898">https://www.jianshu.com/p/64f3b9c22898</a></p>
<h1 id="理解-C-虚函数表"><a href="#理解-C-虚函数表" class="headerlink" title="理解 C++ 虚函数表"></a>理解 C++ 虚函数表</h1><h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>虚表是 C++ 中一个十分重要的概念，面向对象编程的多态性在 C++ 中的实现全靠虚表来实现。在聊虚表之前我们先回顾一下什么是多态性。</p>
<p>多态实际上就是让一个父类指针，通过赋予子类对象的地址，可以呈现出多种形态和功能。如果这么说比较抽象的话，我们看一个例子就明白了：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Base</span> &#123;</span></span><br><span class="line">    <span class="keyword">int</span> m_tag;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Base</span>(<span class="keyword">int</span> tag) : <span class="built_in">m_tag</span>(tag) &#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">print</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Base::print() called&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">vPrint</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Base::vPrint() called&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">printTag</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Base::m_tag of this instance is: &quot;</span> &lt;&lt; m_tag &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Derived</span> :</span> <span class="keyword">public</span> Base &#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Derived</span>(<span class="keyword">int</span> tag) : <span class="built_in">Base</span>(tag) &#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">print</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Derived1::print() called&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">vPrint</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Derived::vPrint() called&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们声明了一个父类 <code>Base</code>，和它的一个派生类 <code>Derived</code>，其中 <code>print()</code> 实例方法是非虚函数，而其余两个实例方法被声明为了虚函数。并且在子类中我们重新了 <code>print()</code> 和 <code>vPrint()</code>。下面我们构造出一个 <code>Derived</code> 实例，并分别将其地址赋给 <code>Base</code> 指针和 <code>Derived</code> 指针：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> *argv[])</span> </span>&#123;</span><br><span class="line">    Derived *foo = <span class="keyword">new</span> <span class="built_in">Derived</span>(<span class="number">1</span>);</span><br><span class="line">    Base *bar = foo;</span><br><span class="line">    </span><br><span class="line">    foo-&gt;<span class="built_in">print</span>();</span><br><span class="line">    foo-&gt;<span class="built_in">vPrint</span>();</span><br><span class="line">    </span><br><span class="line">    bar-&gt;<span class="built_in">print</span>();</span><br><span class="line">    bar-&gt;<span class="built_in">vPrint</span>();</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们看看程序运行的结果：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Derived1::<span class="built_in">print</span>() <span class="function">called</span></span><br><span class="line"><span class="function"><span class="title">Derived::vPrint</span><span class="params">()</span> called</span></span><br><span class="line"><span class="function"><span class="title">Base::print</span><span class="params">()</span> called</span></span><br><span class="line"><span class="function"><span class="title">Derived::vPrint</span><span class="params">()</span> called</span></span><br></pre></td></tr></table></figure>

<p>可以看到，对于 <code>Derived</code> 指针的操作正如它应该表现的样子，然而当我们把相同对象的地址赋给 <code>Base</code> 指针时，可以发现它的非虚函数竟然表现出了父类的行为，并没有被重写的样子。</p>
<p>这是什么原因呢？</p>
<h1 id="C-类的实质是什么"><a href="#C-类的实质是什么" class="headerlink" title="C++ 类的实质是什么"></a>C++ 类的实质是什么</h1><p>首先我们要明白 C++ 中类的实质到底是什么。实际上，类在 C++ 中就是 <strong>struct</strong> （结构体）的一种扩展，允许了更高级的继承和虚函数。那么也就是说，结构体缺少的实际上就是虚函数。</p>
<p>对于一般的成员变量，它和结构体在内存布局上是完全一样的，不管是顺序还是内存对齐，完全一致。而一个类的方法地址并不会存储在一个实例的内存中。对于非虚函数，它们在内存中的地址是唯一的，你可以把它想象成普通函数，只不过第一个参数是 <code>this</code> 指针，在通过类对象指针调用时，编译器会根据类型找到相应非虚函数的地址，这个工作是编译时完成的。</p>
<p><img src="/2021/11/10/%E7%90%86%E8%A7%A3C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8/1507403-fdadc14d4e99d1d2.png" alt="1.1"></p>
<p>也就是说，什么指针指向什么函数这是固定的，反正指针如果是 <code>Base *</code>，那我就直接执行 <code>Base::print()</code> 函数。</p>
<h1 id="揭开-vTable-的神秘面纱"><a href="#揭开-vTable-的神秘面纱" class="headerlink" title="揭开 vTable 的神秘面纱"></a>揭开 vTable 的神秘面纱</h1><p>既然非虚函数实现这么简单，那虚函数是不是会很复杂？其实并不是那么复杂。虚函数的地址被存储一张叫做虚表的东西里，我们其实很容易拿到这个虚表。下面我们通过 dump memory 的方式来揪出一个类的虚表：</p>
<p><img src="/2021/11/10/%E7%90%86%E8%A7%A3C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8/1.2.png" alt="1.2"></p>
<p>看到我选中的那个字节，那是我们的一个实例变量，在这个实例变量的前面有 8 个字节的内容，那实际就是虚表的地址了，我们尝试将这个地址所指向的内容拿出来：</p>
<p><img src="/2021/11/10/%E7%90%86%E8%A7%A3C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8/1.3.png" alt="1.3"></p>
<p>这就是虚表的内容了，什么？你不信，下面我就把虚表中第一个函数揪出来执行一下：</p>
<p><img src="/2021/11/10/%E7%90%86%E8%A7%A3C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8/1.4.png" alt="1.4"></p>
<p>可以看到，<code>Derived</code> 类中重写的 <code>vPrint()</code> 方法已经被执行。这就说明虚函数在执行时是一个动态的过程，并不是在编译时就确定下来要执行哪一个函数，而是运行时从虚表查到真正要执行的函数的地址，然后再将 <code>this</code> 指针传入执行。</p>
<p>到这里，我们已经大致了解了虚函数是怎样工作的了。下面我们看看 <code>Base</code> 类和 <code>Derived</code> 类的虚表有什么区别。我修改了源码，实例化了一个 <code>Base</code> 类对象 <code>baz</code>，然后分别 dump 出 <code>Base</code> 类和 <code>Derived</code> 类的内存：</p>
<p><img src="/2021/11/10/%E7%90%86%E8%A7%A3C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8/1.5.png" alt="1.5"></p>
<p>可以看出，两个对象的虚表指针是不同的。然后我们看看这两者虚表有什么不同：</p>
<p><img src="/2021/11/10/%E7%90%86%E8%A7%A3C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8/1.6.png" alt="1.6"></p>
<p>这两张虚表的第一个函数不同，因为 <code>Derived</code> 类重写了 <code>vPrint()</code> 方法，所以 <code>Derived</code> 的虚表第一个函数指针会有不同，而 <code>printTag()</code> 我并没有重写，所以两张表指向一个同一个函数。</p>
<p>所以每个类都会维护一张虚表，编译时，编译器根据类的声明创建出虚表，当对象被构造时，虚表的地址就会被写入这个对象内存的起始位置。这就是多态性在 C++ 中实现的方式，而像 Java、OC 这样的语言由于 Runtime 的存在，这些对象会有多余的内存空间记录类的信息（meta-object），在运行时根据这些信息解析出相应的函数去执行。虽然不同，但是异曲同工。</p>
<p>理解虚函数表有什么作用呢？</p>
<ul>
<li>能让你更好地理解 C++</li>
<li>一些 hook 技术就是利用虚表来实现的</li>
</ul>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">LiYang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://example.com/2021/11/10/理解C-虚函数表/">http://example.com/2021/11/10/理解C-虚函数表/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2021/12/02/%E4%BD%8D%E5%9B%BE%E6%8E%92%E5%BA%8F/"><i class="fa fa-chevron-left">  </i><span>位图排序</span></a></div><div class="next-post pull-right"><a href="/2021/10/09/C-emplace-back/"><span>C++_emplace_back</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2013 - 2022 By LiYang</div><div class="framework-info"><span>Driven - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>Theme - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script></body></html>